import logging

from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from verifications import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger("django")


class SMSCodeView(APIView):
    """
    发送短信验证码
    传入参数：
        mobile, image_code_id, text
    """

    def get(self, request, mobile):
        redis_conn = get_redis_connection("verify_codes")
        send_flag = redis_conn.get(f"send_flag_{mobile}")
        if send_flag:
            return Response(
                {"message": "手机号发送短信验证码频繁"}, status=status.HTTP_400_BAD_REQUEST
            )
        sms_code = "6666"  # todo 先写死验证码测试用
        logger.info(f"mobile:{mobile}_msm_code:{sms_code}")
        pl = redis_conn.pipeline()
        pl.setex(
            f"sms_{mobile}", constants.SMS_CODE_REDIS_EXPIRES, sms_code
        )
        pl.setex(f"send_flag_{mobile}", constants.SMS_CODE_REDIS_EXPIRES, 1)
        pl.execute()
        send_sms_code.delay(mobile, sms_code)
        return Response({"message": "OK"}, status=status.HTTP_200_OK)
